<template>
  <div class="app-container">
    <el-card style="max-width: 100%" shadow="always">
      <template #header>
        <div class="card-header">
          <span>直播管理</span>
        </div>
      </template>
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
<!--        <el-form-item label="所属用户id" prop="userId">-->
<!--          <el-input-->
<!--              v-model="queryParams.userId"-->
<!--              placeholder="请输入所属用户"-->
<!--              clearable-->
<!--              @keyup.enter="handleQuery"-->
<!--          />-->
<!--        </el-form-item>-->
        <el-form-item label="直播标题" prop="title">
          <el-input
              v-model="queryParams.title"
              placeholder="请输入直播标题"
              clearable
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="好视通会议ID" prop="hstMeetingId">
          <el-input
              v-model="queryParams.hstMeetingId"
              placeholder="请输入好视通会议ID"
              clearable
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="状态" clearable>
                <el-option
                        v-for="dict in liveStatus"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                />
            </el-select>
        </el-form-item>
        <el-form-item label="直播日期" prop="liveDate">
            <el-date-picker
                    v-model="queryParams.liveDate"
                    type="daterange"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
            </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
              type="danger"
              :icon="Plus"
              @click="handleAdd"
          >创建</el-button>
        </el-col>
        <el-col :span="1.5">
            <el-button
                    type="warning"
                    plain
                    :icon="Download"
                    size="mini"
                    @click="handleExport"
            >导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

<!--        <el-tag closable>直播统计实际直播时长次日可查看</el-tag>-->

      <el-table v-loading="loading" :data="liveList" border @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">>
<!--        <el-table-column type="selection" width="55" align="center" />-->
        <el-table-column label="ID" align="center" prop="id" />
        <el-table-column label="会议ID" align="center" prop="hstMeetingId"/>
          <el-table-column label="发起人" align="center" prop="userId"/>
        <el-table-column label="直播主题" align="center" prop="title"/>
        <el-table-column label="直播详情" align="center" prop="detail" />
        <el-table-column label="直播开始时间" align="center" prop="startTime" width="180px">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="直播结束时间" align="center" prop="endTime" width="180px">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="观看人数" align="center" prop="viewCount" />
        <el-table-column label="实际直播时长" align="center" prop="durationText" width="120px"/>
        <el-table-column label="状态" align="center" prop="status" >
          <template #default="scope">
            <dict-tag :options="liveStatus" :value="scope.row.status" />
          </template>
        </el-table-column>
<!--        <el-table-column label="推流地址" align="center" prop="pushUrl" />-->
        <el-table-column label="创建时间" align="center" prop="createTime" width="180px">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="修改时间" align="center" prop="updateTime" width="180px">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="直播控制" align="center" width="180px">
            <template #default="scope">
              <el-button-group v-if="scope.row.status !== 3 && scope.row.isDelete === 0">
                <el-button type="primary" @click="startLive(scope.row)" v-if="scope.row.status == 0">开始</el-button>
                <el-button type="warning" @click="pauseLive(scope.row)" v-if="scope.row.status == 1">暂停</el-button>
                <el-button type="success" @click="recoveryLive(scope.row)" v-if="scope.row.status == 2">恢复</el-button>
                <el-button type="danger" @click="stopLive(scope.row)" v-if="scope.row.status == 1">停止</el-button>
              </el-button-group>
            </template>
        </el-table-column>
        <el-table-column label="观众信息" align="center" width="180px">
          <template #default="scope">
            <el-button-group>
              <el-button type="primary" @click="showAudience(scope.row)">查看</el-button>
              <el-button type="danger" v-if="scope.row.status !== 3 && scope.row.isDelete === 0" @click="settingAudience(scope.row)">设置</el-button>
            </el-button-group>
          </template>
        </el-table-column>
<!--        <el-table-column label="统计信息" align="center" width="90px">-->
<!--          <template #default="scope">-->
<!--            <el-button type="primary" @click="showStat(scope.row)">查看</el-button>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="操作"  align="center" width="150px" fixed="right">
          <template #default="scope">
            <el-dropdown split-button type="primary" v-if="scope.row.isDelete === 0">
              更多
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="scope.row.status !== 3" ><el-button link type="primary"  @click="setting(scope.row)" >设置</el-button></el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.status !== 3" ><el-button link type="primary"  @click="layoutSetting(scope.row)" >布局</el-button></el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.status !== 3"><el-button link type="primary"   @click="viewLive(scope.row)" >观看</el-button></el-dropdown-item>
                  <el-dropdown-item><el-button link type="primary"  @click="viewReplay(scope.row)" >回放</el-button></el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.status !== 3"><el-button link type="danger"   @click="handleUpdate(scope.row)" >修改</el-button></el-dropdown-item>
                  <el-dropdown-item><el-button link type="danger"  @click="handleDelete(scope.row)" >删除</el-button></el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改直播对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="liveRef" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="好视通会议号" prop="hstMeetingId">
              <el-input v-model="form.hstMeetingId" placeholder="请输入好视通会议号"/>
          </el-form-item>
          <el-form-item label="直播标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入直播标题" />
          </el-form-item>
          <el-form-item label="直播详情" prop="detail">
            <el-input v-model="form.detail" placeholder="请输入直播详情" />
          </el-form-item>
          <el-form-item label="观看密码" prop="password">
            <el-input v-model="form.password" placeholder="请输入观看密码" />
          </el-form-item>
          <el-form-item label="直播录像" prop="detail">
              <el-tooltip class="item" effect="dark" content="注意：创建后将不可更改" placement="right">
                  <el-switch
                          :disabled="updateFlag"
                          v-model="form.isRecord"
                          active-color="#13CBD3"
                          inactive-color="#909399">
                  </el-switch>
              </el-tooltip>
          </el-form-item>
          <el-form-item label="直播开始时间" prop="startTime">
            <el-date-picker
                popper-class="hide-time"
                clearable
                :readonly="updateFlag"
                v-model="form.startTime"
                type="datetime"
                format="YYYY/MM/DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择直播开始时间"
                :default-value="new Date(new Date().getTime())"
                :disabled-date="timePickerDisabledDate"
            />
          </el-form-item>
          <el-form-item label="直播结束时间" prop="endTime">
            <el-date-picker
                popper-class="hide-time"
                clearable
                :readonly="updateFlag"
                v-model="form.endTime"
                type="datetime"
                format="YYYY/MM/DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择直播结束时间"
                :default-value="new Date(new Date().getTime())"
                :disabled-date="endTimePickerDisabledDate"
            />
          </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 设置对话框 -->
    <el-dialog title="直播设置" v-model="settingOpen" width="600px" append-to-body>
      <el-form ref="settingRef" :model="settingForm" label-width="120px">
        <el-form-item label="直播观看密码" prop="password">
          <el-input type="password" v-model="settingForm.password" show-password/>
        </el-form-item>
        <el-form-item label="直播台标" prop="waterLogo">
          <image-upload v-model="settingForm.waterLogo" :limit="1"/>
        </el-form-item>
        <el-form-item label="直播会场名" prop="waterName">
          <el-input v-model="settingForm.waterName" placeholder="请输入直播水印会场名" />
        </el-form-item>
        <!--        <el-form-item label="直播水印时间" prop="waterTime">-->
        <!--          <el-switch v-model="settingForm.waterTime"-->
        <!--                     active-text="显示"-->
        <!--                     inactive-text="隐藏"-->
        <!--                     active-value="1"-->
        <!--                     inactive-value="0"></el-switch>-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSettingForm">确 定</el-button>
          <el-button @click="cancelSetting">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 直播布局设置 -->
    <el-dialog title="直播布局设置" v-model="layoutSettingOpen" width="600px" append-to-body>
      <el-form ref="layoutSettingRef" :model="layoutSettingForm" label-width="120px">
        <el-form-item label="布局模式" prop="layoutMode">
          <el-radio-group v-model="layoutSettingForm.layoutMode">
            <el-radio-button label="1">
              <template #default="scope">
                <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="视频双屏布局"
                    placement="bottom"
                >
                  <div>
                    <el-icon style="vertical-align: middle">
                      <Reading />
                    </el-icon>
                    <span style="vertical-align: middle"> 双屏 </span>
                  </div>
                </el-tooltip>
              </template>
            </el-radio-button>
            <el-radio-button label="2">
              <template #default="scope">
                <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="演讲者视频数据分隔1+5布局"
                    placement="bottom"
                >
                  <div>
                    <el-icon style="vertical-align: middle">
                      <Mic />
                    </el-icon>
                    <span style="vertical-align: middle"> 演讲者 </span>
                  </div>
                </el-tooltip>
              </template>
            </el-radio-button>
            <el-radio-button label="3">
              <template #default="scope">
                <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="画中画视频数据叠加1+5布局"
                    placement="bottom"
                >
                  <div>
                    <el-icon style="vertical-align: middle">
                      <Money />
                    </el-icon>
                    <span style="vertical-align: middle"> 画中画 </span>
                  </div>
                </el-tooltip>
              </template>
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="窗口显示数量" prop="maxVideoCount">
            <el-input-number v-model="layoutSettingForm.maxVideoCount" :min="1" :max="9" ></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitLayoutSetting">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="观众信息" v-model="audienceOpen" width="1200px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
            <el-button
                    type="warning"
                    plain
                    :icon="Download"
                    size="mini"
                    @click="handleExportAudience"
            >导出</el-button>
        </el-col>
      </el-row>
      <el-table :data="audienceList">
        <el-table-column label="ID" align="center" prop="id" />
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column label="电话" align="center" prop="phone" />
        <el-table-column label="单位" align="center" prop="unit" />
        <el-table-column label="部门" align="center" prop="department" />
        <el-table-column label="职位" align="center" prop="position" />
        <el-table-column label="邮箱" align="center" prop="email" />
        <el-table-column label="性别" align="center" prop="gender" />
        <el-table-column label="QQ" align="center" prop="qq" />
        <el-table-column label="微信" align="center" prop="wx" />
      </el-table>

      <pagination
          v-show="audienceTotal>0"
          :total="audienceTotal"
          v-model:page="audienceQueryParams.pageNum"
          v-model:limit="audienceQueryParams.pageSize"
          @pagination="getAudienceList"
      />
    </el-dialog>

    <el-dialog title="观众信息设置" v-model="audienceSettingOpen" width="600px" append-to-body>
      <el-form ref="audienceSettingRef" :model="audienceSettingForm" label-width="120px">
        <el-form-item label="观众需填信息" prop="needFields">
          <el-checkbox-group v-model="audienceSettingForm.needFields">
            <el-checkbox label="name">姓名</el-checkbox>
            <el-checkbox label="phone" >电话</el-checkbox>
            <el-checkbox label="unit" >单位
            </el-checkbox>
            <el-checkbox label="department" >部门
            </el-checkbox>
            <el-checkbox label="position" >职位
            </el-checkbox>
            <el-checkbox label="email" >邮箱
            </el-checkbox>
            <el-checkbox label="gender" >性别
            </el-checkbox>
            <el-checkbox label="qq" >QQ
            </el-checkbox>
            <el-checkbox label="wx" >微信
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="需显示水印信息" prop="waterFields">
          <el-checkbox-group v-model="audienceSettingForm.waterFields">
            <el-checkbox label="name">姓名</el-checkbox>
            <el-checkbox label="phone" >电话</el-checkbox>
            <el-checkbox label="unit" >单位
            </el-checkbox>
            <el-checkbox label="department" >部门
            </el-checkbox>
            <el-checkbox label="position" >职位
            </el-checkbox>
            <el-checkbox label="email" >邮箱
            </el-checkbox>
            <el-checkbox label="gender" >性别
            </el-checkbox>
            <el-checkbox label="qq" >QQ
            </el-checkbox>
            <el-checkbox label="wx" >微信
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAudienceSettingForm">确 定</el-button>
          <el-button @click="cancelAudienceSetting">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="直播统计信息" v-model="statsOpen" width="800px">
      <el-row justify="center" style="text-align: center">
        <el-col :span="12">
          <el-statistic title="总观看数" :value="liveStat.viewCount" />
        </el-col>
        <el-col :span="12">
          <el-statistic title="实际直播时长" :value="liveStat.duration" :formatter="durationFormat">
          </el-statistic>
        </el-col>
      </el-row>
    </el-dialog>

    <el-dialog title="录像回放" v-model="liveReplayOpen" width="1200px">
      <el-table :data="liveVideos" empty-text="暂无直播回放录像，请稍后再试！需要在录制结束5分钟后才能获取到数据。">
        <el-table-column label="视频ID" align="center" prop="videoId" />
        <el-table-column label="创建时间" align="center" prop="videoCreateTime" >
          <template #default="scope">
            <span>{{ parseTime(scope.row.videoCreateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="录像文件" align="center" prop="url" >
          <template #default="scope">
            <el-button-group>
              <el-button type="primary" @click="viewLiveVideo(scope.row)">观看</el-button>
              <el-button type="danger" @click="downloadLiveVideo(scope.row)">下载</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="Live">
import {
  listLive,
  getLive,
  delLive,
  addLive,
  updateLive,
  controlLive,
  settingLive,
  statLive,
  getLiveReplay,
  getLiveLayout, changeLiveLayout
} from "@/api/live.js";
import { listAudience } from "@/api/audience.js";
import { getAudienceSetting, updateAudienceSetting } from "@/api/audienceSetting.js";
import { useRoute, useRouter } from "vue-router";
import {msToTime} from "@/utils/common.js";
import {Mic, Money, Plus, Reading, Download} from "@element-plus/icons-vue";
import {checkSign} from "@/api/api.js";

const { proxy } = getCurrentInstance();

const liveList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const settingOpen = ref(false);

const updateFlag = ref(false);

const liveStatus = ref([
  {
    label: "就绪",
    value: 0,
    elTagType: "info"
  },
  {
    label: "直播中",
    value: 1,
    elTagType: "primary"
  },
  {
    label: "暂停",
    value: 2,
    elTagType: "warning"
  },
  {
    label: "结束",
    value: 3,
    elTagType: "danger"
  }
]);

const data = reactive({
  form: {},
  settingForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    title: null,
    isSuper: 0,
    hstMeetingId: null,
    liveDate: null
  },
  rules: {
    title: [
        { required: true, message: "直播标题不能为空", trigger: "blur" }
    ],
    startTime: [
      { required: true, message: "直播开始时间必填", trigger: "blur" }
    ],
    endTime: [
      { required: true, message: "直播结束时间必填", trigger: "blur" }
    ]
  }
});

function tableRowClassName({row, rowIndex}) {
    if (row.isDelete === 1) {
        return 'danger-row';
    }
    return '';
}


const { queryParams, form, rules, settingForm } = toRefs(data);

/**
 * @description: 获取路由参数
 * @type {RouteLocationNormalizedLoaded}
 */
const route = useRoute();
const router = useRouter();

const userId = route.query.userId;
let hstMeetingId = route.query.meetingId;
const superAdmin = route.query.superAdmin;
const timeStamp = route.query.timeStamp;
const sign = route.query.sign;

if(hstMeetingId && hstMeetingId !== "") {
    queryParams.value.hstMeetingId = hstMeetingId;
}

// referer校验
// const referer = document.referrer;
// console.log("referer:", referer);
// if (referer && referer.indexOf(import.meta.env.VITE_MEETING_DOMAIN) !== -1) {
//     if(!userId || !hstMeetingId || !superAdmin || !timeStamp || !sign) {
//         router.push({ path: "/error/401" });
//     }
// } else {
//     console.error('referer is invalid');
//     router.push({ path: "/error/401" });
// }

if(!userId || !hstMeetingId || !superAdmin || !timeStamp || !sign) {
    router.push({ path: "/error/401" });
} else {
  // getList();
  // TODO: 简单前端处理过期时间校验
  // 判断timeStamp距离当前时间是否超过15分钟
  if((Date.now() - Number(timeStamp)) > 15 * 60 * 1000) {
      console.error("已过期，无权访问");
      router.push({ path: "/error/401" });
  } else {
      const checkSignReq = {
          userId: userId,
          meetingId: hstMeetingId,
          superAdmin: superAdmin,
          timeStamp: timeStamp,
          sign: sign
      };
      checkSign(checkSignReq).then(response => {
          if(!response.data) {
              router.push({ path: "/error/401" });
          } else {
              getList();
          }
      }).catch((e) => {
          console.error(e);
          router.push({ path: "/error/401" });
      });
  }
}

/** 查询直播列表 */
function getList() {
  loading.value = true;
  if ('true' !== superAdmin) {
      queryParams.value.userId = userId;
      queryParams.value.isSuper = 0;
  } else {
      queryParams.value.userId = null;
      queryParams.value.isSuper = 1;
  }
  let queryParamsCopy = JSON.parse(JSON.stringify(queryParams.value));
  if (queryParams.value.liveDate && queryParams.value.liveDate.length > 0) {
      queryParamsCopy.startTime = queryParams.value.liveDate[0];
      queryParamsCopy.endTime = queryParams.value.liveDate[1];
  }
  delete queryParamsCopy.liveDate;
  listLive(queryParamsCopy).then(response => {
    liveList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    userId: null,
    title: null,
    detail: null,
    password: null,
    startTime: null,
    endTime: null, // waterLogo: null,
    hstMeetingId: null
  };
  proxy.resetForm("liveRef");
}

/** 设置表单重置 */
function resetSetting() {
  settingForm.value = {
    password: null,
    waterLogo: null,
    waterName: null,
    waterTime: null,
  };
  proxy.resetForm("settingRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  // queryParams.value.hstMeetingId = null;
  // queryParams.value.title = null;
  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 创建按钮操作 */
function handleAdd() {
  reset();
  updateFlag.value = false;
  if(hstMeetingId) {
    form.value.hstMeetingId = hstMeetingId;
  }
  form.value.userId = userId;

  open.value = true;
  title.value = "创建直播";
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  updateFlag.value = true;
  const id = row.id || ids.value;
  getLive(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改直播";
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$modal.loading("正在处理，请稍候...");
  proxy.$refs["liveRef"].validate(valid => {
    if (valid) {
      if (form.value.id != undefined) {
        updateLive(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
          proxy.$modal.closeLoading()
        }).catch(()=>{
          proxy.$modal.closeLoading()
        });
      } else {
          proxy.$modal.confirm("确认创建吗？会自动删除之前已创建的直播").then(() => {
              addLive(form.value).then(response => {
                  proxy.$modal.msgSuccess("创建成功");
                  open.value = false;
                  getList();
                  proxy.$modal.closeLoading()
              }).catch(()=>{
                  proxy.$modal.closeLoading()
              });
          })
      }
    } else {
      proxy.$modal.closeLoading()
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id || ids.value;
  proxy.$modal.loading("正在处理，请稍候...");
  proxy.$modal.confirm('是否确认删除直播编号为"' + ids + '"的数据项？').then(function() {
    return delLive(ids);
  }).then(() => {
    getList();
    proxy.$modal.closeLoading()
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
    proxy.$modal.closeLoading()
  });
}

/** 导出按钮操作 */
// 导出观众信息
function handleExportAudience() {
    const params = {
        "liveId": curLiveId.value
    }
    proxy.download("audience/export", `观众信息_${new Date().getTime()}.xlsx`, { ...params });
}
// 导出直播信息
function handleExport() {
    let queryParamsCopy = JSON.parse(JSON.stringify(queryParams.value));
    if (queryParams.value.liveDate && queryParams.value.liveDate.length > 0) {
        queryParamsCopy.startTime = queryParams.value.liveDate[0];
        queryParamsCopy.endTime = queryParams.value.liveDate[1];
    }
    delete queryParamsCopy.liveDate;
    proxy.download("live/export",`直播信息_${new Date().getTime()}.xlsx`, queryParamsCopy)
}

/**
 * 开启直播
 * @param row
 */
function startLive(row) {
    proxy.$modal.loading("正在处理，请稍候...");
  controlLive(row.id, "start").then(response => {
      proxy.$modal.closeLoading()
    proxy.$modal.msgSuccess("操作成功");
    getList();
  }).catch(() => {
      proxy.$modal.closeLoading()
  });
}

/**
 * 结束直播
 * @param row
 */
function stopLive(row) {
    proxy.$modal.loading("正在处理，请稍候...");
  controlLive(row.id, "stop").then(response => {
      proxy.$modal.closeLoading()
    proxy.$modal.msgSuccess("操作成功");
    getList();
  }).catch(() => {
      proxy.$modal.closeLoading()
  });
}

/**
 * 暂停直播
 * @param row
 */
function pauseLive(row) {
  proxy.$modal.loading("正在处理，请稍候...");
  controlLive(row.id, "pause").then(response => {
    proxy.$modal.closeLoading()
    proxy.$modal.msgSuccess("操作成功");
    getList();
  }).catch(() => {
    proxy.$modal.closeLoading()
  });
}

/**
 * 恢复直播
 * @param row
 */
function recoveryLive(row) {
  proxy.$modal.loading("正在处理，请稍候...");
  controlLive(row.id, "recovery").then(response => {
    proxy.$modal.closeLoading()
    proxy.$modal.msgSuccess("操作成功");
    getList();
  }).catch(() => {
    proxy.$modal.closeLoading()
  });
}

/**
 * 设置直播
 * 权限和水印
 * @param row
 */
function setting (row) {
  resetSetting();
  const id = row.id;
  getLive(id).then(response => {
    settingForm.value = response.data;
    settingOpen.value = true;
  });
}
function submitSettingForm() {
  settingLive(settingForm.value).then(response => {
    proxy.$modal.msgSuccess("设置成功");
    settingOpen.value = false;
  });
}
function cancelSetting() {
  settingOpen.value = false;
  resetSetting();
}

/**
 * 直播布局设置
 * @param row
 */
const layoutSettingOpen = ref(false);
const layoutSettingForm = ref({});
function layoutSetting (row) {
  const id = row.id;
  getLiveLayout(id).then(response => {
    layoutSettingForm.value = response.data;
    layoutSettingOpen.value = true;
  });
}
function submitLayoutSetting() {
  changeLiveLayout(layoutSettingForm.value).then(response => {
    proxy.$modal.msgSuccess("设置成功");
    layoutSettingOpen.value = false;
  });
}

/**
 * 观看直播
 * @param row
 */
function viewLive (row) {
  const {href} = router.resolve({
    path: '/live',
    query: {
      id: row.id
    }
  })

  // 自动复制直播观看地址
  let clipboard = navigator.clipboard || {
    writeText: (text) => {
      let copyInput = document.createElement('input');
      copyInput.value = text;
      document.body.appendChild(copyInput);
      copyInput.select();
      document.execCommand('copy');
      document.body.removeChild(copyInput);
    }
  }
  if (clipboard) {
    clipboard.writeText(import.meta.env.VITE_LIVE_HOST + href);
    proxy.$message.success("直播观看地址已复制到剪切板");
  }

  // window.open(href, '_blank')
  // 延迟跳转
  setTimeout(function() {
    window.open(import.meta.env.VITE_LIVE_HOST + href, '_blank')
  }, 1000);
}

/**
 * 查看回放
 */
const liveVideos = ref([]);
const liveReplayOpen = ref(false);
function viewReplay (row) {
  proxy.$modal.loading("正在处理，请稍候...");
  getLiveReplay(row.id).then(response => {
    proxy.$modal.closeLoading();
    liveVideos.value = response.data;
    liveReplayOpen.value = true;
  }).catch((()=>{
    proxy.$modal.closeLoading();
  }));
}
function viewLiveVideo(row) {
  if(!row.playUrlList || row.playUrlList.length === 0) {
      proxy.$message.error("暂无直播回放录像，请稍后再试");
      return
  }
  const {href} = router.resolve({
    path: '/replay',
    query: {
      url: row.playUrlList[0].playUrl
    }
  })
  window.open(href, '_blank')
}
function downloadLiveVideo(row) {
  if(!row.playUrlList || row.playUrlList.length === 0) {
      proxy.$message.error("暂无直播回放录像，请稍后再试");
      return
  }
  // 下载录像视频文件
  // proxy.download(row.url, {}, `live_video_${new Date().getTime()}.mp4`);
  window.open(row.playUrlList[0].playUrl, '_blank')
}


/**
 * 直播观众信息
 */
const audienceTotal = ref(0);
const audienceList = ref([]);
const audienceQueryParams = ref({
  liveId: null,
  pageNum: 1,
  pageSize: 10
})
function getAudienceList(row) {
  if(row.id) {
    audienceQueryParams.value.liveId = row.id;
  }
  listAudience(audienceQueryParams.value).then(response => {
    audienceList.value = response.rows;
    audienceTotal.value = response.total;
  });
}

let curLiveId = ref(null);
const audienceOpen = ref(false);
function showAudience(row) {
  audienceOpen.value = true;
  getAudienceList(row);
  curLiveId.value = row.id;
}

/**
 * 观众信息设置
 */
const  audienceSettingOpen = ref(false);
const audienceSettingForm = ref({});

function settingAudience (row) {
  resetAudienceSetting();
  const id = row.id;
  getAudienceSetting(id).then(response => {
    audienceSettingForm.value = response.data;
    if(audienceSettingForm.value.needFields) {
      audienceSettingForm.value.needFields = audienceSettingForm.value.needFields.split(",");
    } else {
      audienceSettingForm.value.needFields = [];
    }
    if(audienceSettingForm.value.waterFields) {
      audienceSettingForm.value.waterFields = audienceSettingForm.value.waterFields.split(",");
    } else {
      audienceSettingForm.value.waterFields = [];
    }
    audienceSettingOpen.value = true;
  });
}

function submitAudienceSettingForm() {
  let audienceSettingFormCopy = JSON.parse(JSON.stringify(toRaw(audienceSettingForm.value)));
  audienceSettingFormCopy.needFields = audienceSettingFormCopy.needFields.join(",");
  audienceSettingFormCopy.waterFields = audienceSettingFormCopy.waterFields.join(",");
  updateAudienceSetting(audienceSettingFormCopy).then(response => {
    proxy.$modal.msgSuccess("修改成功");
    audienceSettingOpen.value = false;
  });
}

function cancelAudienceSetting() {
  audienceSettingOpen.value = false;
  resetAudienceSetting();
}
function resetAudienceSetting() {
  audienceSettingForm.value = {};
}

/**
 * 查看统计信息
 */
const statsOpen = ref(false);
const liveStat = ref({});
function showStat(row) {
  proxy.$modal.loading("正在处理，请稍候...");
  statLive(row.id).then(response => {
    proxy.$modal.closeLoading();
    liveStat.value = response.data;
    if(!liveStat.value.viewCount) {
      liveStat.value.viewCount = 0;
    }
    // liveStat.value.viewCount = 1111;
    // liveStat.value.duration = 360000;
    statsOpen.value = true;
  }).catch(()=>{
    proxy.$modal.closeLoading();
  });
}
function durationFormat (duration) {
  return msToTime(duration);
}

/**
 * 创建直播开始结束时间校验
 * 开始时间只能输入未来时间
 * 结束是看必须大于开始时间
 */
const timePickerDisabledDate = (time) => {
  return time.getTime() <= Date.now();
}
const endTimePickerDisabledDate = (time) => {
  // 如果没有选择开始时间，则禁用所有时间
  if (!form.value.startTime) {
    return true;
  }
  return time.getTime() <= new Date(form.value.startTime).getTime();
}
</script>

<style lang="scss">
.hide-time {
  .el-picker-panel__footer .el-picker-panel__link-btn:first-child {
    display: none;
  }
}
.el-table .danger-row {
  background: #C0C4CC;
}
</style>
